<?php
namespace lib;

/**
 * 数据模型类的父类，所有的数据模型类要继承此类
 *
 * @package lib
 */
class Model
{
    private $pdo;
    protected $table;
    protected $pk;

    /**
     * model constructor.
     * @param $table 表名
     * @param $pk 主键名
     */
    public function __construct()
    {
        //require 'functions.php';
        $config=require '../config/database.php';
        $host=$config['host'];
        $dbname=$config['dbname'];
        $dsn="mysql:host=$host;dbname=$dbname";
        $this->pdo=new \Pdo($dsn,$config['username'],$config['password']);
    }

    public function get(Array $data=[]){
        //select * from students where id=4 and name='小黄';
        $sets='';
        foreach($data as $k=>$v){
            $sets.=$k."='".$v."' and ";
        }
        $sets=rtrim($sets,'and ');

        if(empty($data)){
            $sql="select * from ".$this->table;
        }else{
            $sql="select * from ".$this->table." where ".$sets.";";
        }
        $res=$this->pdo->query($sql);
        $rows=$res->fetchAll(\PDO::FETCH_ASSOC);
        return  $rows;
    }


    /**
     * @param array $data 要操作的数据
     */
    public function save(Array $data){
        $sets='';
        foreach($data as $k=>$v){
            $sets.=$k."='".$v."',";
        }
        $sets=rtrim($sets,',');
        if(isset($data[$this->pk])){  //如果用户有传主键字段就为update
            $sql="update ".$this->table." set ".$sets." where ".$this->pk."=".$data[$this->pk].";";
        }else{
            $sql="insert into ".$this->table." set ".$sets.";";
        }
        $res=$this->pdo->exec($sql);
        if($res){
            return '修改成功!';
        }else{
            return '修改失败!';
        }
    }

    public function join(Array $data,Array $condition=[]){
        $joins='';
        $conditions='';
        foreach($data as $k=>$v){
            $joins.=' join '.$k.' on '.$this->table.$this->pk.'='.$k.$v;
        }
        if(!empty($condition)){
            foreach($condition as $k=>$v){
                $conditions.=$k."='".$v."' and ";
            }
            $conditions=rtrim($conditions,'and ');
        }

        $sql="select * from ".$this->table.$joins.$conditions.";";
        $res=$this->pdo->query($sql);
        $rows=$res->fetchAll(\PDO::FETCH_ASSOC);
        return  $rows;
    }

    public function delete(Array $data){
        $sets='';
        foreach($data as $k=>$v){
            $sets.=$k."='".$v."' and ";
        }
        $sets=rtrim($sets,'and ');
        $sql="delete from ".$this->table." where ".$sets.";";

        $res=$this->pdo->exec($sql);
        if($res){
            return '删除成功!';
        }else{
            return '删除失败!';
        }
    }
}
